from info import sr
from info.constants import HOME_PAGE_MAX_NEWS
from info.models import User, News, Category
from info.modules.home import home_blu
import logging  # python内置的日志模块, 可以将日志在控制台打印, 也可以写入到文件中
# flask中的默认的打印信息也是使用logging模块实现的, 但是没有写入到日志文件中
from flask import current_app, render_template, session, jsonify, request, abort

# 2. 使用蓝图对象来注册路由
from info.utils.response_code import RET, error_map


@home_blu.route('/')
def index():
    # flask中封装了logging语法, 可以在打印日志时显示日志位置
    # current_app.logger.error("出现了错误")
    user_id = session.get("user_id")
    user = None  # type: User
    if user_id:  # 用户已登录
        # 查询出用户数据
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    news_list = []
    # 查询点击量前10的新闻数据, 传入模板
    try:
        new_list = News.query.order_by(News.clicks.desc()).limit(HOME_PAGE_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)

    news_list = [news.to_dict() for news in new_list]

    # 查询所有的分类数据
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return abort(500)

    user = user.to_dict() if user else None

    # 使用后端渲染来展示首页，将数据传入模板渲染
    return render_template("news/index.html", user=user, news_list=news_list, categories=categories)


# 设置网站小图标
@home_blu.route("/favicon.ico")
def favicon():
    return current_app.send_static_file("news/favicon.ico")


# 获取新闻列表
@home_blu.route("/get_news_list")
def get_news_list():
    # 获取参数
    cid = request.args.get("cid")
    cur_page = request.args.get("cur_page")
    per_count = request.args.get("per_count", HOME_PAGE_MAX_NEWS)

    # 校验参数
    if not all([cid, cur_page]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        cid, cur_page, per_count = [int(x) for x in (cid, cur_page, per_count)]
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 判断是否为最新
    cid_list = [News.status == 0]
    if cid != 1:
        cid_list.append(News.category_id == cid)

    # 按照发行时间查询和排列数据 返回数据
    pn = None
    try:
        pn = News.query.filter(*cid_list).order_by(News.create_time.desc()).paginate(cur_page, per_count)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 返回json
    data = {
        "news_list": [news.to_dict() for news in pn.items] if pn else [],
        "total_page": pn.pages
    }
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)
